package com.lyc.task.service;

import com.lyc.common.enums.CategoryLevel;
import com.lyc.common.model.BookInfo;
import com.lyc.common.model.Category;
import com.lyc.common.repository.BookInfoRepository;
import com.lyc.common.repository.CategoryRepository;
import com.lyc.task.config.BookUrlConfig;
import com.lyc.utils.RandomUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 廖师兄
 * 2017-05-22 22:43
 */
//@Service
@Slf4j
@Data
@Service
public class QishuService {

    private final static String HOST = "http://www.qisuu.com";

    private String outId;

    @Autowired
    private BookInfoRepository bookInfoRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private BookUrlConfig bookUrlConfig;

    /**
     * 获取最新的书籍列表
     */
    public List<String> fetchList() {
        val outIdList = new ArrayList<String>();

        Document doc = null;
        try {
            doc = Jsoup.connect("http://www.qisuu.com/s/new/").get();
        } catch (HttpStatusException e) {
            log.warn("最新列表url不能访问={}");
            e.printStackTrace();
        }catch (Exception e) {

        }

        Elements elements = doc.select("div.listBox li a");
        for (Element element : elements) {
            String url = element.attr("href");
            if (!url.startsWith("/Writer")) {
                //例如 /123.html -> 123
                outIdList.add(url.substring(1, url.length() - 5));
            }
        }
        return outIdList;

    }

    @Transactional
    public void run() {
        //先从数据库查询, 如果有了则不继续
        val bookInfoSelect = bookInfoRepository.findByBookOutId(outId);
        if (bookInfoSelect != null) {
            log.warn("数据库中已有这本书, bookOutId={}", outId);
            return;
        }

        Document doc = null;
        String url = "";
        try {
            url = String.format(bookUrlConfig.getQishu(), outId);
            doc = Jsoup.connect(url).get();
        } catch (HttpStatusException e) {
            log.warn("url不能访问={}", url);
            return;
        }catch (Exception e) {

        }
        Elements categoryList = doc.select("div.position span a");

        //父类目id
        Category categoryParent = this.getCategory(categoryList.get(1));
        log.info("父类目id={}", categoryParent);

        //子类目id
        Category categorySon = this.getCategory(categoryList.get(2));
        log.debug("子类目id={}", categorySon);

        //书名
        String bookName = categoryList.get(3).text();
        log.debug("书名={}", bookName);

        //图书封面
        String bookImage = doc.select("div.detail_pic img").get(0).attr("src");
        log.debug("封面={}", bookImage);

        //下载次数(阅读量)
        String readCount = doc.select("div.detail_right li").get(1).text()
                .replace("下载次数：", "");
        log.debug("下载次数={}", readCount);

        //发布时间
        String publishTimeString = doc.select("div.detail_right li").get(4).text()
                .replace("发布日期：", "");
        LocalDate publishTime = LocalDate.parse(publishTimeString);
        log.debug("发布时间={}", publishTime);

        //作者
        String author = doc.select("div.detail_right li").get(6).text()
                .replace("书籍作者：", "");
        log.debug("作者={}", author);

        //星级
        String starString = doc.select("div.detail_right li em").get(0).attr("class");
        Integer star = Integer.valueOf(starString.substring(starString.length() - 1, starString.length()));
        log.debug("星级={}", star);

        //简介
        String description = doc.select("div.showInfo").text();
        log.debug("简介={}", description);

        //下载链接
        String downloadUrl = doc.select("div.showDown li a").get(1).attr("href");
        log.debug("下载链接={}", downloadUrl);

        //写入类目数据库
        categoryParent.setCategoryLevel(CategoryLevel.PARENT.getCode());
        categorySon.setCategoryLevel(CategoryLevel.SON.getCode());
        categorySon.setCategoryParentId(categoryParent.getCategoryId());
        categoryRepository.save(categorySon);
        categoryRepository.save(categoryParent);

        //写入书籍数据库
        BookInfo bookInfo = new BookInfo();
        String bookId = RandomUtil.id();
        bookInfo.setBookId(bookId);
        bookInfo.setBookName(bookName);
        bookInfo.setBookAuthor(author);
        bookInfo.setBookImage(bookImage);
        bookInfo.setBookDownloadUrl(downloadUrl);
        bookInfo.setBookDescription(description);
        bookInfo.setCategoryId(categorySon.getCategoryId());
        bookInfo.setBookOutId(String.valueOf(outId));

        ZoneId zone = ZoneId.systemDefault();
        Instant instant = publishTime.atStartOfDay().atZone(zone).toInstant();
        bookInfo.setPublishTime(Date.from(instant));

        bookInfo.setBookReadCount(Integer.valueOf(readCount));
        bookInfoRepository.save(bookInfo);
    }

    /**
     * 从url字符串中获取类目id
     * @param element
     * @return
     */
    private Category getCategory(Element element) {
        Category category = new Category();
        String name = element.text();
        String url = element.attr("href");
        String pattern = "(\\d+)(?=/$)";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(url);
        if (m.find()) {
            category.setCategoryId(Integer.valueOf(m.group()));
            category.setCategoryName(name);
            return category;
        } else {
            throw new IllegalArgumentException("url中匹配不到类目id");
        }
    }
}
